package com.mini.auth.service;

import com.mini.admin.api.entity.SysOauthClient;
import com.mini.admin.api.openfeign.AdminOAuthClientOpen;
import com.mini.auth.enums.PasswordEncoderTypeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Service;

/**
 * 用于根据 client_id 查询 client 信息
 * @author Zhou Feng
 */
@Service
public class ClientDetailsServiceImpl implements ClientDetailsService {
    @Autowired
    private AdminOAuthClientOpen clientService;
    ThreadLocal<ClientDetails> threadLocal = new ThreadLocal<>();

    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        if (clientId==null||"".equals(clientId.trim())){
            throw new NoSuchClientException("无效客户端");
        }
        //查看缓存中是否有client
        if (threadLocal.get()!=null){
            return threadLocal.get();
        }
        SysOauthClient client = clientService.getClientByClientId(clientId).getData();
        if (client==null){
            throw new NoSuchClientException("客户端未注册");
        }
        BaseClientDetails clientDetails = new BaseClientDetails(
                client.getClientId(),
                client.getResourceIds(),
                client.getScope(),
                client.getAuthorizedGrantTypes(),
                client.getAuthorities(),
                client.getWebServerRedirectUri()
        );
        clientDetails.setClientSecret(PasswordEncoderTypeEnum.NOOP.getPrefix()+client.getClientSecret());
        clientDetails.setAccessTokenValiditySeconds(client.getAccessTokenValidity());
        clientDetails.setRefreshTokenValiditySeconds(client.getRefreshTokenValidity());
        threadLocal.set(clientDetails);
        return clientDetails;
    }
}
